package com.njitzx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

public class getScore {
    private static String url = "http://jwjxnew.njit.edu.cn/jwglxt/cjcx/cjcx_cxXsgrcj.html?doType=query&gnmkdm=N305005";
    public static final String APP_ID = "";
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";
    public  static  final String targetUrl = "http://ehall.njit.edu.cn/new/index.html";
    public static void main(String[] args) {
        String cookie = getCookie();
        List<Score> scores = getScores(cookie);
        for (int i = 0; i < scores.size(); i++) {
            Score score=scores.get(i);
            System.out.print(score.getCourseName()+" ");
            System.out.print(score.getScore());
            System.out.println();
        }
    }
    public static  List<Score>  getScores(String cookie){
        Map<String, String> params = new HashMap<>();
        params.put("xnm", "2023");
        params.put("xqm", "12");
        params.put("kcbj", "");
        params.put("_search", "false");
        params.put("nd", "1726950030586");
        params.put("queryModel.showCount", "50");
        params.put("queryModel.currentPage", "1");
        params.put("queryModel.sortName", "");
        params.put("queryModel.sortOrder", "asc");
        params.put("time", "0");

        String responseBody = executePostRequest(url, params,cookie);
        //打印了响应结果
        System.out.println("响应结果: " + responseBody);

        JSONObject jsonObject = JSON.parseObject(responseBody);
        JSONArray kbList = jsonObject.getJSONArray("items"); //拿到所有的成绩

        List<Score> scores = new ArrayList<>();
        for (Object o : kbList) {
            JSONObject jsonObject1 = (JSONObject) o;
            String StudentName = jsonObject1.getString("xm");
            String StudentId = jsonObject1.getString("xh");
            String courseName = jsonObject1.getString("kcmc");
            String grade = jsonObject1.getString("cj");
            String type = jsonObject1.getString("kcxzmc") + "课";
            double credit = Double.parseDouble(jsonObject1.getString("xf"));
            Score score = new Score(null, StudentName, StudentId, courseName, type, credit, grade);
            scores.add(score);
        }
        return scores;
    }
    public  static  String getCookie(){
        Path p1 = Paths.get("src", "chromedriver-win64", "chromedriver.exe");
        //设置系统环境
        System.setProperty("webdriver.chrome.driver", p1.toAbsolutePath().toString());

        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get(targetUrl);
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(50));

        WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/article[1]/article/div[1]/div[1]")));
        element.click();

        //获取用户名和密码
        WebElement username = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));
        WebElement password = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("password")));
        username.sendKeys("");
        password.sendKeys("");


        WebElement captchaElement = driver.findElement(By.id("captchaImg")); //扎到这个元素
        File screenshot = captchaElement.getScreenshotAs(OutputType.FILE);  //进行截图
        File destinationFile = new File("captcha.png");
        try {
            FileHandler.copy(screenshot, destinationFile); //将截图拷贝到当前目录下面来
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        String path = destinationFile.getAbsolutePath();
        org.json.JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
        String wordsResultJson = res.get("words_result").toString();
        JSONArray wordsResultArray = JSON.parseArray(wordsResultJson);

        JSONObject firstResult = wordsResultArray.getJSONObject(0);
        String words = firstResult.getString("words");
        String rescode = words.replaceAll(" ", ""); //去掉空格
        System.out.println(rescode);
        WebElement code = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("captchaResponse")));
        code.sendKeys(rescode);

        //点击登录按钮
        WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"casLoginForm\"]/p[5]/button")));
        loginButton.click();

        WebElement teach = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/article[5]/section/div[2]/div[1]/div[3]/pc-card-html-5131446170220455-01/amp-w-frame/div/div[2]/div/div[1]/widget-app-item[1]/div/div/div[2]/div[1]")));
        teach.click();

        for (String winHandle : driver.getWindowHandles()) {
            driver.switchTo().window(winHandle);
        }
        //因为需要等待五秒钟  五秒钟后可以直接刷新页面即可进来
        driver.navigate().refresh();


        Map<String, String> map = new HashMap<>();
        Set<Cookie> cookies = driver.manage().getCookies();  //拿到所有的cookie 存放到map中去

        for (Cookie cookie : cookies) {
            map.put(cookie.getName(), cookie.getValue());
        }
        StringBuffer sb = new StringBuffer();
        sb.append("JSESSIONID=" + map.get("JSESSIONID") + ";");
        sb.append("iPlanetDirectoryPro=" + map.get("iPlanetDirectoryPro") + ";");
        sb.append("route=" + map.get("route"));
        return sb.toString();
    }

    public static String executePostRequest(String targetURL, Map<String, String> params, String cookie) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String responseBody = null; // 用于存储响应内容
        try {
            // 创建一个HttpPost实例，设置请求的URL
            HttpPost httpPost = new HttpPost(targetURL);
            // 设置请求头，模拟AJAX请求
            httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36");
            httpPost.setHeader("Host", "ensdp.njit.edu.cn:10443");
            httpPost.setHeader("Origin", "https://ensdp.njit.edu.cn:10443");
            httpPost.setHeader("Referer", "https://ensdp.njit.edu.cn:10443/http/webvpn3e1a11b7208e283ab07ade5d2913fc13d6f6fe09d2dc7372db2a51a14aa4167a/jwglxt/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default");
            httpPost.setHeader("Cookie", cookie);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

            // 将参数转换为表单数据格式
            String postParams = params.entrySet().stream()
                    .map(entry -> entry.getKey() + "=" + entry.getValue())
                    .collect(Collectors.joining("&"));

            StringEntity entity = new StringEntity(postParams, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            // 执行POST请求，获取HttpResponse对象
            HttpResponse response = httpClient.execute(httpPost);
            System.out.println(httpPost.getURI());
            // 获取响应的状态码并打印
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("状态码: " + statusCode);
            // 获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应实体转换为字符串
                responseBody = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (ClientProtocolException e) {
            // 处理客户端协议异常
            throw new RuntimeException(e);
        } catch (IOException e) {
            // 处理I/O异常
            throw new RuntimeException(e);
        } finally {
            // 确保关闭HttpClient对象，释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        System.out.println(responseBody);
        return responseBody;
    }
}
